<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { UserApi } from '@/api/UserApi.ts'
import type { UserVO, searchParams } from '@/api/User.ts'

interface RankRecord extends UserVO {
  passRate?: string
  rank: number
}

const columns = [
  {
    title: '排名',
    dataIndex: 'rank',
    key: 'rank',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '提交数',
    dataIndex: 'submit',
    key: 'submit',
    align: 'center',
  },
  {
    title: '通过数',
    dataIndex: 'solved',
    key: 'solved',
    align: 'center',
  },
  {
    title: '通过率',
    dataIndex: 'passRate',
    key: 'passRate',
    align: 'center',
  },
]

const loading = ref(false)
const tableData = ref<RankRecord[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const baseParams: searchParams = {
  id: null,
  account: null,
  gender: null,
}

const formatPassRate = (record: Pick<UserVO, 'submit' | 'solved'>) => {
  const submit = Number(record?.submit ?? 0)
  const solved = Number(record?.solved ?? 0)
  if (!submit || submit <= 0) return '0.00%'
  const rate = (solved / submit) * 100
  return `${rate.toFixed(2)}%`
}

const sortRecords = (records: UserVO[]): RankRecord[] => {
  const offset = (pagination.current - 1) * pagination.pageSize
  return [...records]
    .sort((a, b) => {
      if (b.solved !== a.solved) {
        return b.solved - a.solved
      }
      const aTime = new Date(a.createTime).getTime()
      const bTime = new Date(b.createTime).getTime()
      return aTime - bTime
    })
    .map((item, index) => ({
      ...item,
      passRate: formatPassRate(item),
      rank: offset + index + 1,
    }))
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...baseParams,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    }
    const data = await UserApi.search(params as any)
    const records = data?.records ?? []
    tableData.value = sortRecords(records)
    pagination.current = data?.pageNumber ?? pagination.current
    pagination.pageSize = data?.pageSize ?? pagination.pageSize
    pagination.total = data?.totalRow ?? records.length
  } finally {
    loading.value = false
  }
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 20
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="flex justify-center px-4 py-6">
    <a-card
      title="排行榜"
      class="w-full max-w-[1080px] rounded-lg shadow-sm"
    >
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'rank'">
            <span>{{ record.rank }}</span>
          </template>
          <template v-else-if="column.key === 'passRate'">
            <span>{{ record.passRate }}</span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
